import "./style/index.css";
import "./js/slider";
import { EUV } from "@hongweifei/euv";
import { getUserInfo, logout as userLogout } from "./api/user";
import { StatusCode } from "./api/web-result";
import { clearDiscussion, getDiscussion, publishDiscussion } from "./api/discussion";


new EUV({
    elementSelector: "#app",
    async mounted() {
        setInterval(() => {
            const date = new Date();
            this.data.nowTime = date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        }, 500);

        const userInfoResult = await getUserInfo();
        if (userInfoResult.code === StatusCode.SUCCESS) {
            this.data.user = userInfoResult.data ? userInfoResult.data : {};
            this.data.login = true;
        }

        const disscusionResult = await getDiscussion();
        if (disscusionResult.code === StatusCode.SUCCESS) {
            this.data.discussionDataSource = disscusionResult.data;
        }
    },

    data: {
        nowTime: (function() {
            const date = new Date();
            return date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        })(),
        user: {},
        login: false,
        discussionDataSource: []
    },

    methods: {
        logout() {
            userLogout();
            this.data.user = {};
            this.data.login = false;
        },

        gotoCreateWJ() {
            if (!this.data.login) {
                alert("请先登录");
                return;
            }
            window.location.href = "./pages/list.html";
        },

        gotoViewWJ() {
            if (!this.data.login) {
                alert("请先登录");
                return;
            }
            window.location.href = "./pages/list.html";
        },

        /**
         * @param { Event } e
         */
        async publishDiscussion(e) {
            e.preventDefault();

            /** @type { HTMLElement } */
            const formElement = e.target;
            /** @type { HTMLTextAreaElement } */
            const textareaElement = formElement.querySelector("textarea");

            const result = await publishDiscussion(textareaElement.value);
            alert(result.message);
            this.data.discussionDataSource = (await getDiscussion()).data;
            if (result.code === StatusCode.SUCCESS) {
                textareaElement.value = "";
            }
        },

        async clickClearDiscussion() {
            const result = await clearDiscussion();
            alert(result.message);
            if (result.code === StatusCode.SUCCESS) {
                this.data.discussionDataSource = [];
            }
        }
    }
});


